import { useCallback, useEffect } from 'react';
import { Toast } from 'esy-ui';
import { useGlobalStore } from '@/mobx';
import { postColletGame, postGameAuth, postUserColletGameList } from '@/services';
import { useNavigation } from './useNavigation';
import { lsSetItem } from '@/utils';
import { useOtherStore } from '@/mobx/other';

/** 游戏收藏和点击逻辑处理 */
export const useGame = (token?: string, isDef = false) => {
  const { changeState } = useGlobalStore();
  const navigation = useNavigation();
  const { updataCollets, isCollet } = useOtherStore();

  // 点击游戏的逻辑
  const clickGame = useCallback(
    (id: number) => {
      changeState('isLoading', true);
      if (id) {
        postGameAuth({ GameID: id, IsTry: false, IsPC: false })
          .then((res: any) => {
            // 加载成功跳转到游戏
            navigation(`/game/${id}`);
            lsSetItem('game_ing_id', res?.Data);
          })
          .catch((err) => {
            console.info(err);
            // TODO Token 过期时才需要跳转登录
            if (err) {
              navigation('/login');
            }
          })
          .finally(() => {
            changeState('isLoading', false);
          });
      } else {
        Toast.show({ content: 'no GameID!' });
      }
    },
    [changeState, navigation],
  );

  // 获取收藏数据
  const getColletList = useCallback(() => {
    if (!token) return;
    postUserColletGameList({})
      .then((res: any) => {
        // 保存到全局
        updataCollets(res?.Data);
      })
      .catch(() => {
        Toast.show({ content: 'get Collet List Failed!' });
      })
      .finally(() => {
        changeState('isLoading', false);
      });
  }, [changeState, token, updataCollets]);

  // 默认加载
  useEffect(() => {
    if (isDef) {
      getColletList();
    }
  }, [getColletList, isDef]);

  // 点击收藏
  const clickCollct = useCallback(
    (gId: number) => {
      if (!token) return;
      changeState('isLoading', true);
      // 收藏游戏
      postColletGame({ GameID: gId, Type: isCollet(gId) ? 2 : 1 })
        .then(() => {
          getColletList();
        })
        .catch(() => {
          Toast.show({ content: 'Collet Game Failed!' });
          changeState('isLoading', false);
        });
    },
    [changeState, getColletList, isCollet, token],
  );

  return { clickGame, clickCollct };
};
